package com.vben.ai.handler;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.vben.ai.cache.SocketClientCache;
import com.vben.ai.constant.ModelConstant;
import com.vben.ai.service.ChatService;
import com.vben.ai.service.EduAssistant;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.UUID;

@Component
@SuppressWarnings("unused")
public class SocketIOHandler {

    @Resource
    private ChatService chatService;

    @Resource
    private EduAssistant eduAssistant;

    @OnConnect
    public void onConnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        UUID sessionId = client.getSessionId();
        SocketClientCache.saveClient(userId, sessionId, client);
        System.out.println("userId: " + userId + "连接建立成功 - " + sessionId);
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        UUID sessionId = client.getSessionId();
        SocketClientCache.deleteSessionClientByUserId(userId, sessionId);
        System.out.println("userId: " + userId + "连接关闭成功 - " + sessionId);
    }

    @OnEvent(value = ModelConstant.DEEP_SEEK_R1)
    public void deepSeekChatEvent(SocketIOClient client, AckRequest ackRequest, String message) {
        Flux<String> stream = chatService.stream(ModelConstant.DEEP_SEEK_R1, message);
        stream.subscribe(item -> {
                    client.sendEvent("response", item);
                },
                error -> {
                    System.out.println("发生错误");
                },
                () -> {
                    System.out.println("end");
                });
    }

    @OnEvent(value = ModelConstant.Qwen_Max)
    public void qwenMaxChatEvent(SocketIOClient client, AckRequest ackRequest, String message) {
        Flux<String> stream = chatService.stream(ModelConstant.Qwen_Max, message);
        stream.subscribe(item -> {
                    client.sendEvent("response", item);
                },
                error -> {
                    System.out.println("发生错误");
                },
                () -> {
                    System.out.println("end");
                });
    }

    @OnEvent(value = "edu")
    public void eduChatEvent(SocketIOClient client, AckRequest ackRequest, String message) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        Flux<String> stream = eduAssistant.chat(message);
        stream.subscribe(item -> {
            client.sendEvent("response", item);
        });
    }
}
